package itcast.shops.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import itcast.domain.User;
import itcast.domain.CarBean;
import itcast.domain.ShopsBean;
import itcast.service.ShopsService;
import itcast.service.ShopsServiceimpl;

/**
 * 添加商品到购物车
 */
@WebServlet("/carshops")
public class CarshopsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CarshopsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1、设置编码防止乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		int uid = 0;
		//2、获取商品的id
		String shopid=request.getParameter("shopid");
		//3、获取商品对象准备存入购物车中
			//1、调用service查询商品对象
			ShopsService services=new ShopsServiceimpl();
			ShopsBean sBean=services.findshopid(shopid);
		//4、获取当前User
		User user=(User) request.getSession().getAttribute("user");
		if (user==null) {
			//如果user为空证明未登录跳转至登录页面
			request.setAttribute("lose", "你还没有登录，先登录一下吧！");
			//转发到登录页面，并提示你还没有登陆
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			
		}else {
			//用户已经登陆
			    uid=user.getUserid();
		}
		//5、调用shopservice添加
		if (uid==0) {
			//防止uid=0去在数据库里面添加数据
			//直接重定向到原来的界面
			response.sendRedirect(request.getHeader("Referer"));
		}
	   //6、调用service去查询购物车对象如果在里面查出对应id与对应shopid则直接添加
		ShopsService service=new ShopsServiceimpl();
		List<CarBean> car=service.findcarshop(Integer.toString(uid));
		int toal=0;
		for(CarBean cars:car){
			if (Integer.toString(cars.getUserid()).equals(Integer.toString(uid))&&Integer.toString(cars.getShopid()).equals(shopid)) {
			
				service.updatecarshop(shopid,uid,cars.getCounts()+1);
				toal=1;
				break;
			}
	     }
		  //如果查询到购物车中已经存在调用service更新，没查询到就在购物车中添加相应商品
		if (toal==0) {
			services.addshop(shopid,uid,sBean);
		}
		
		 response.sendRedirect(request.getHeader("Referer"));
	}
}

